package com.example.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 *
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问, 但是功能页只有对应权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //无权限, 进入默认登录页面, 开启这个会给你一个/login页面, 这是自带的
        http.formLogin().loginPage("/tologin").loginProcessingUrl("/login");
        //开启了注销功能, 在首页中添加一个导向/toLogin的链接, 会导向注销并导向/login?logout页面
        //同时还有很多别的选项
        http.logout().logoutSuccessUrl("/index");
        //开启记住我功能
        http.rememberMe();
    }

    //认证, 密码必须要编码, PasswordEncoder, 否则可以反编译
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("ray1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                .and()
                .withUser("ray2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("ray3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
